package com.meal.entity.model.wx;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.meal.common.redis.IRedis;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: yzh->WechatTokenUtil
 * @description:
 * @author: yangzhanghui
 * @create: 2019-09-10 13:25
 **/
@Component
public class WechatTokenUtil {

    @Autowired
    private IRedis redis;

    public final static Logger log = LoggerFactory.getLogger(WechatTokenUtil.class);

    /**
     * 发送微信统一消息api接口
     */
    public static final String WechatUniformMessagePostUrl = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=";
    /**
     * 获取access_token api接口
     */
    public static final String WechatAccessTokenPostUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
    /**
     * 获取openid api接口
     */
    public static final String WechatGetOpenIdPostUrl = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    private final String appId = "wxfc8ac78730b382bb";

    private final String appSecret = "f33488df0dc0add565c2561c06202c0e";


    private static final String appId2 = "wxfc8ac78730b382bb";

    private static final String appSecret2 = "f33488df0dc0add565c2561c06202c0e";

    public static String getAccessToken(){
        Map<String, Object> param = new HashMap<>();
        param.put("appid", appId2);
        param.put("secret", appSecret2);
        String result = HttpUtil.post(WechatAccessTokenPostUrl, param);
        JSONObject jo = JSON.parseObject(result);
        return jo.getString("access_token");
    }

    /**
     * 获取微信access_token
     * @return
     */
    public com.meal.entity.model.wx.AccessToken getWechatAccessToken(){
        if(!StringUtils.isBlank(appId)&&!StringUtils.isBlank(appSecret)){
            Map<String, Object> param = new HashMap<>();
            param.put("appid", appId);
            param.put("secret", appSecret);
            try {
                Long createTime = redis.hget("wx_access_token", "create_time", Long.class);
                if(createTime == null || (System.currentTimeMillis() > createTime + 7200 * 1000)){
                    String result = HttpUtil.post(WechatAccessTokenPostUrl, param);
                    log.debug("请求微信接口获取access_token的回显:[{}]",result);
                    if(!StringUtils.isBlank(result) && result.contains("7200")){//7200
                        JSONObject jo = JSON.parseObject(result);
                        //success
                        String accessToken = jo.getString("access_token");
                        String expiresIn = jo.getString("expires_in");

                        log.debug("获取access_token:[{}]",accessToken);
                        redis.hset("wx_access_token", "create_time", System.currentTimeMillis());
                        redis.hset("wx_access_token", "expires_in", expiresIn);
                        redis.hset("wx_access_token", "access_token", accessToken);
                        return new com.meal.entity.model.wx.AccessToken(accessToken, Long.parseLong(expiresIn));
                    }
                }else {
                    return new com.meal.entity.model.wx.AccessToken(redis.hget("wx_access_token", "access_token", String.class),
                            redis.hget("wx_access_token", "expires_in", Long.class));
                }
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }

    /**
     * 请求方法
     * @param requestUrl
     * @param requestMethod
     * @param outputStr
     * @return
     */
    public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
        try {

            URL url = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            conn.setRequestMethod(requestMethod);
            conn.setRequestProperty("content-type", "application/json");
            // 当outputStr不为null时向输出流写数据
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意编码格式
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            // 从输入流读取返回内容
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            conn.disconnect();
            return buffer.toString();
        } catch (ConnectException ce) {
            ce.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}